'use strict'

import React, { Component } from 'react'
import Drawer from '../Drawer'
import noop from 'lodash/noop'
import './style.scss'

export default class Picker extends Component {
    constructor(props) {
        super(props)
        this.state = {
            open: this.props.open
        }
        this.handleDrawerDismiss = this.handleDrawerDismiss.bind(this)
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.open !== this.state.open) {
            this.setState({
                open: nextProps.open
            })
        }
    }

    handleClickOption(option) {
        this.props.onPick(option)
        this.setState({
            open: false
        })
    }

    handleDrawerDismiss() {
        this.props.onDismiss()
    }

    render() {
        return (
            <Drawer onDismiss={this.handleDrawerDismiss} open={this.state.open}>
                <div className="ddui-picker">
                    <ul className="table-view">
                        {
                            this.props.options.map((option, index) =>
                                    <li key={index} onClick={this.handleClickOption.bind(this, option)} className="table-view-cell">{option.text}</li>
                            )
                        }
                    </ul>
                </div>
            </Drawer>
        )
    }
}

Picker.defaultProps = {
    open: false,
    onPick: noop,
    onDismiss: noop,
    options: []
}

Picker.propTypes = {
    open: React.PropTypes.bool,
    onPick: React.PropTypes.func,
    onDismiss: React.PropTypes.func,
    options: React.PropTypes.array
}